import { computed, defineComponent, reactive, ref, toRaw, unref } from 'vue';
import './index.less';
import { Icon } from '/@/components/Icon';
import { useRouter } from 'vue-router';
import { cloneDeep, concat, find, filter } from 'lodash-es';
import Title from '/@/views/gateruler/components/Title';
import type { DeckCardItem } from '/@/api/gateruler/model/deckModel';
import { AbilityEnum, CardList, CardListQuery, ClassEnum } from '/@/api/gateruler/model/cardModel';
import { Button, ConfigProvider, Empty, Field, List } from 'vant';
import { awaitWrap, filterNullAttributes, judgeSystem } from '/@/utils';
import { CardListApi } from '/@/api/gateruler/card';
import BaseSearch from '/@/views/gateruler/components/CardSearch/BaseSearch';
import SeriesSearch from '/@/views/gateruler/components/CardSearch/SeriesSearch';
import AttrsSearch from '/@/views/gateruler/components/CardSearch/AttrsSearch';
import DeckCardDetail from '/@/views/gateruler/components/DeckCardDetail/DeckCardDetail';
import { useGateRulerStore } from '/@/store/modules/gateruler';
import { appShareUsing } from '/@/utils/appInteractive';
import { useOptions } from '/@/views/gateruler/hooks/useOptions';
import ChooseCardPopup from './components/ChooseCardPopup';

export default defineComponent({
  name: 'GateRulerDeckCardPage',
  setup() {
    // 设置分享参数
    appShareUsing({} as any);

    const router = useRouter();
    const leftClick = () => {
      router.back();
    };

    const gaterulerStore = useGateRulerStore();
    const { rulerGroupCard } = useOptions();
    const rulerObject = rulerGroupCard(gaterulerStore.getCreateDeckParams.ruler.other_ename!);

    const queryState = reactive<CardListQuery>({
      page: 1,
      page_size: 30,
      message: '',
      series_id: [],
      card_class: [],
      card_category: [],
      rarity: [],
      legion: [],
      level: [],
      ability: [],
      attrs: [],
    });
    const searchFieldSlot = {
      button: () => {
        return (
          <Button
            type={'primary'}
            size={'small'}
            onClick={() => {
              getList(true);
            }}
          >
            搜索
          </Button>
        );
      },
    };

    // 数据获取
    const listLoading = ref(false); // 是否处于加载状态 默认不处于，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<CardList>({
      total: 0,
      rows: [],
    });

    const getList = async (isRefresh: boolean) => {
      if (isRefresh) {
        queryState.page = 1;
        listLoading.value = true;
        listData.rows = [];
      }
      const params: CardListQuery = filterNullAttributes(queryState, []);
      const [error, data] = await awaitWrap(CardListApi(toRaw(params)));
      if (error) {
        return;
      }
      const result = data as CardList;
      if (queryState.page === 1) {
        listData.total = result.total;
        listFinished.value = false;
        !result.total ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      queryState.page += 1;
      listLoading.value = false;
      if (listData.rows.length >= listData.total) {
        listFinished.value = true;
      }
    };
    // 卡牌校验
    const validationCardNum = (card: DeckCardItem) => {
      let color = '';
      //传奇卡逻辑
      if (card.card_class === ClassEnum.L) {
        // 找到所有同名传奇牌
        const sameLegends = filter(unref(allSelectCards), ['other_ename', card.other_ename]);
        let sameLegendCount = 0;
        sameLegends.map((item) => {
          sameLegendCount += item.number!;
        });
        if (rulerObject.maxSameLegendCard >= 0 && sameLegendCount > rulerObject.maxSameLegendCard) {
          color = '!bg-red-500';
          return color;
        }

        // 找到所有的传奇牌
        const legends = filter(unref(allSelectCards), ['card_class', ClassEnum.L]);
        let legendCount = 0;
        legends.map((item) => {
          legendCount += item.number!;
        });
        if (rulerObject.maxLegendTotal >= 0 && legendCount > rulerObject.maxLegendTotal) {
          color = '!bg-red-500';
          return color;
        }
      }

      // 同名卡逻辑
      const sameCars = filter(unref(allSelectCards), ['other_ename', card.other_ename]);
      let sameCount = 0;
      sameCars.map((item) => {
        sameCount += item.number!;
      });
      if (rulerObject.maxSameCard >= 0 && sameCount > rulerObject.maxSameCard) {
        color = '!bg-red-500';
        return color;
      }
      return color;
    };
    const GetCardItem = ({ cardList }: { cardList: CardList }) => {
      const listArr: VueNode[] = [];
      const CardAction = ({ card }: { card: DeckCardItem }) => {
        const target = find(unref(allSelectCards), ['card_id', card.card_id]);
        target ? (card.number = target.number) : (card.number = 0);
        const color = validationCardNum(card);
        return (
          <ConfigProvider
            themeVars={{ buttonBorderWidth: 0 }}
            class={'card-action-buttons flex justify-between absolute bg-white'}
          >
            <Button
              plain
              icon={'minus'}
              size={'small'}
              type='primary'
              round
              disabled={!card.number}
              onClick={() => {
                delCardClick(card);
              }}
            />
            <span class={`card-nums ${color} ${card.number ? '' : 'hidden'}`}>x{card.number}</span>
            <Button
              plain
              icon={'plus'}
              size={'small'}
              type='primary'
              round
              onClick={() => {
                addCardClick(card);
              }}
            />
          </ConfigProvider>
        );
      };
      cardList.rows.map((item) => {
        listArr.push(
          <li class={'card-item'}>
            <div class='image'>
              <img
                src={item.img}
                alt=''
                onClick={() => {
                  detailState.value = true;
                  detailCardIdState.value = item.card_id;
                }}
              />
            </div>
            <div class={'name-box'}>
              <div class={'name-content van-ellipsis text-xs text-white px-md'}>
                [{item.is_foil ? '闪' : '平'}]{item.name}
              </div>
            </div>
            <CardAction card={item} />
          </li>
        );
      });
      return <ul class='card-list flex flex-wrap'>{listArr}</ul>;
    };

    // 筛选Popup
    const searchState = ref(false);
    const seriesPopupState = ref(false);
    const attrsPopupState = ref(false);
    // 打开其他条件筛选
    const filterClick = () => {
      searchState.value = true;
    };
    // 打开系列筛选
    const seriesPopupClick = () => {
      seriesPopupState.value = true;
    };
    // 打开属性筛选
    // @ts-ignore
    const attrsPopupClick = () => {
      attrsPopupState.value = true;
    };

    // 详情
    const detailState = ref(false);
    const detailCardIdState = ref(0);

    // 适配安卓键盘
    const bottomSearchClass = ref('');
    const fieldFocusClick = () => {
      console.log(judgeSystem());
      if (judgeSystem() === 'android') {
        bottomSearchClass.value = 'android';
        return false;
      }
      bottomSearchClass.value = '';
    };
    const fieldBlurClick = () => {
      bottomSearchClass.value = '';
    };

    // 已选择卡牌
    const allSelectCards = computed(() => {
      return concat(cloneDeep(unref(cntSelectCards)), cloneDeep(unref(otherSelectCards)));
    });
    const cntSelectCards = ref(cloneDeep(gaterulerStore.getCreateDeckParams.cnt_cards));
    const otherSelectCards = ref(cloneDeep(gaterulerStore.getCreateDeckParams.other_cards));
    const addCardClick = (card: DeckCardItem) => {
      let cardDatas: DeckCardItem[];
      card.ability!.indexOf(AbilityEnum.CNT) >= 0
        ? (cardDatas = unref(cntSelectCards))
        : (cardDatas = unref(otherSelectCards));
      // 判断同一张卡
      const target = find(cardDatas, ['card_id', card.card_id]);
      if (!target) {
        card.number = 1;
        cardDatas.push(card);
        return;
      }
      target.number! += 1;
    };
    const delCardClick = (card: DeckCardItem) => {
      let cardDatas: DeckCardItem[];
      card.ability!.indexOf(AbilityEnum.CNT) >= 0
        ? (cardDatas = unref(cntSelectCards))
        : (cardDatas = unref(otherSelectCards));
      const target = find(cardDatas, ['card_id', card.card_id]);
      if (!target) {
        return;
      }
      target.number! -= 1;
      if (!target.number) {
        let delIndex = 0;
        cardDatas.filter((item, index) => {
          if (item.card_id === target.card_id) {
            delIndex = index;
          }
        });
        cardDatas.splice(delIndex, 1);
      }
    };
    const confirmAddCards = () => {
      gaterulerStore.setCreateDeckCntCard(unref(cntSelectCards));
      gaterulerStore.setCreateDeckOtherCard(unref(otherSelectCards));
      router.back();
    };

    // 已选择卡牌的浮层
    const chooseShowState = ref(false);

    return () => (
      <div class={'gateruler-deck-card-page'}>
        <Title title={'添加单卡'} leftArrow onLeftClick={leftClick} />
        <div class={'card-list-container'}>
          {unref(listEmpty) ? (
            <Empty>未找到相关卡牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多卡牌'}
              onLoad={getList}
            >
              <GetCardItem cardList={listData} />
            </List>
          )}
        </div>
        <div class={`bottom-area flex ${unref(bottomSearchClass)}`}>
          <div class={'bottom-search flex items-center'}>
            <div class={'input-box'}>
              <Field
                v-model={[queryState.message]}
                placeholder='卡牌名称或规则'
                leftIcon={'search'}
                v-slots={searchFieldSlot}
                clearable
                onFocus={fieldFocusClick}
                onBlur={fieldBlurClick}
              />
            </div>
            <div class='svg-button filter text-center' onClick={filterClick}>
              <Icon icon={'single-filter|svg'} size={30} />
              <span class={'block text-sm'}>筛选</span>
            </div>
          </div>
          <Button
            size={'large'}
            type={'primary'}
            class={'add-button'}
            disabled={!unref(allSelectCards).length}
            onClick={confirmAddCards}
          >
            确认添加
          </Button>
        </div>
        <div
          class={'choose-popup-button'}
          onClick={() => {
            chooseShowState.value = true;
          }}
        >
          已选卡牌
        </div>
        <BaseSearch
          v-model={[searchState.value, 'show']}
          queryState={queryState}
          onPageRefresh={() => {
            getList(true);
          }}
          onOpenSeriesPopup={seriesPopupClick}
          onOpenAttrsPopup={attrsPopupClick}
          isDeck={true}
        />
        <SeriesSearch
          v-model={[seriesPopupState.value, 'show']}
          queryState={queryState}
          onPageRefresh={() => {
            getList(true);
          }}
        />
        <AttrsSearch
          v-model={[attrsPopupState.value, 'show']}
          queryState={queryState}
          onPageRefresh={() => {
            getList(true);
          }}
        />
        <DeckCardDetail v-model={[detailState.value, 'show']} cardId={detailCardIdState.value} />
        <ChooseCardPopup
          v-model={[chooseShowState.value, 'show']}
          selectCards={unref(allSelectCards)}
          onAddCard={addCardClick}
          onDelCard={delCardClick}
          validationCardNum={validationCardNum}
        />
      </div>
    );
  },
});
